<?php
namespace app\model;
use think\Db;
use think\Model;

class SystemMenu extends Model
{
    public static function getMenuList()
    {
        $menu_list = SystemMenu::where('status',1)
            ->field("id,pid,title,concat('iconfont ',icon) as icon,href,target,status")
            ->order('sort','desc')
            ->select();
        return $menu_list;
    }
    public static function menuTree()
    {
        $menuList = self::getMenuList();
        $pid = 0;
        $menuTree = self::buildMenuChild($pid,$menuList);
        return $menuTree;
    }
    public static function buildMenuChild($pid,$menuList)
    {
        $treeList = [];
        foreach ($menuList as $v) {
            if ($pid == $v['pid']) {
                $node = $v;
                $child = self::buildMenuChild($v['id'], $menuList);
                if (!empty($child)) {
                    $node['child'] = $child;
                }
                $treeList[] = $node;
            }
        }
        return $treeList;
    }
    public static function submit($data){
        if(isset($data['id']) && $data['id']){
            $res = Db::name('system_menu')->where('id',$data['id'])->update($data);
        }else{
            unset($data['id']);
            $res = Db::name('system_menu')->insert($data);
        }
        return $res;
    }
    public static function delMenu($id)
    {
        $child = SystemMenu::where('pid',$id)->value('id');
        if($child) return json(['code'=>202,'msg'=>'存在子节点,请先删除子节点']);
        $res = SystemMenu::where('id',$id)->delete();
        return json(['code'=>200,'msg'=>'删除成功']);
    }
}
